package com.wonders.frame.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.wonders.frame.common.Enum.InitCommonSourceEnum;
import com.wonders.frame.common.Enum.RemovedCodeEnum;
import com.wonders.frame.core.entity.EntityTemplate;
import com.wonders.frame.entity.AuthDic;
import com.wonders.frame.entity.AuthUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class Commons {
	public static Map<String, String> map = new HashMap<String, String>();
	public static Map<String, String> xztradeMap = new HashMap<String, String>();
	public static Map<String, String> kstradeMap = new HashMap<String, String>();
	public static Map<String, String> zftradeMap = new HashMap<String, String>();
	public static Map<String, String> vehtradeMap = new HashMap<String, String>();
	public static Gson gson = new Gson();


	public static String dealNull(Object o){
		if(o == null||"null".equals(o)){
			return "";
		}
		return String.valueOf(o);
	}
	public static Object dealObj(Object o){
		if(o == null||"null".equals(o)){
			return "";
		}
		return o;
	}
	public static String toJson(Object o){
		if(o == null){
			return "";
		}

		return gson.toJson(o);
	}

	public static String toJson2(Object o){
		if(o == null){
			return "";
		}
		String json = gson.toJson(o);
		return json.substring(1, json.length()-1);
	}

	public static String returnYdObj(String obj, String key, Map<String, String> map){
		StringBuffer str = new StringBuffer();
		str.append(obj).append("（").append(map.get(key)).append("）");
		return str.toString();
	}

	public static String getObjName(Object o){
		String simpleName = o.getClass().getSimpleName();
		return simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
	}

	public static String toJsonResult(Object o){
		return gson.toJson("[{result:" + o + "}]");
	}

	public static String getJsonByObj(Object o){
		ObjectMapper mapper = new ObjectMapper();
		try {
			return "["+mapper.writeValueAsString(o)+"]";
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return "";
		}
	}
	public static boolean equals(Object o1, Object o2){
		if(o1.equals(dealNull(o2))){
			return true;
		}else{
			return false;
		}
	}
	public static Integer returnInteger(String str){
		if(null != str && !str.equals("")){
			return Integer.valueOf(str);
		}else{
			return 0;
		}
	}
	public static Long returnInteger(Object str){
		if(null != str && !str.equals("")){
			return Long.valueOf(str.toString());
		}else{
			return (long) 0;
		}
	}
	public static int returnInt(String str){
		try{
			if(null != str && !str.equals("")){
				return Integer.parseInt(str);
			}else{
				return 0;
			}
		}catch(Exception e){
			return 0;
		}
	}
	public static int returnInt(Object str){
		try{
			if(null != str && !str.equals("")){
				return Integer.parseInt(str.toString());
			}else{
				return 0;
			}
		}catch(Exception e){
			return 0;
		}
	}
	public static String generateContent(String field, Object valOld, Object valNew,
										 Map<String, String> map, Map<String, Map<String, String>> colDicMap){
		if(colDicMap!=null){
			if(colDicMap.get(field)!=null){
				valOld = colDicMap.get(field).get(valOld);
				valNew = colDicMap.get(field).get(valNew);
			}
		}
		StringBuffer str = new StringBuffer();
		str.append("<strong>").append(String.valueOf(map.get(field))).append("</strong>");
		str.append("：	")
				.append("变更前：【").append(dealNull(valOld)).append("】;")
				.append("变更后：【").append(dealNull(valNew)).append("】");
		return str.toString();
	}
	//判断新增、修改
	public static String isAdd(String id){
		if(StringUtils.isBlank(id)){
			return Utils.ChangesType_Add;
		}else{
			return Utils.ChangesType_Update;
		}
	}
	public static String getDate(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date());
	}
	public static String getDate(int date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
		calendar.set(Calendar.DAY_OF_YEAR, dayOfYear - date);
		return sdf.format(calendar.getTime());
	}
	public static String getChangeDay(int day){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar now = Calendar.getInstance();
		now.setTime(new Date());
		now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
		return sdf.format(now.getTime());
	}
	public static List<String> getRangeDay(int startDay, int range){
		List<String> list = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
		for(int i=range;i>startDay;i++){
			Calendar now = Calendar.getInstance();
			now.setTime(new Date());
			now.set(Calendar.DATE, now.get(Calendar.DATE) + i);
			list.add(sdf.format(now.getTime()));
		}
		return list;
	}
	public static String dealNum(Object obj){
		try{
			if(obj==null){
				return "0";
			}
			NumberFormat nf = new DecimalFormat(",###");
			return nf.format(obj);
		}catch(Exception e){
			e.printStackTrace();
			return "0";
		}
	}
	public static String convertStatus(String status){
		if("notNull".equals(status)){
			return "(为空)";
		}else if("unique".equals(status)){
			return "(重复)";
		}
		return "";
	}
	public static Map<String, String> getOrganMap(){
		map.put("hwc", "航务处");
		map.put("mtzx", "码头中心");
		map.put("jgzx", "建管中心");
		map.put("zfzd", "执法总队");
		map.put("ygc", "运管处");
		map.put("jtw", "交通委");
		map.put("xxzx", "信息中心");
		map.put("xzfwzx", "行政服务中心");
		map.put("lzj", "路政局");
		map.put("zjz", "质监站");
		map.put("kszx", "考试中心");
		map.put("zhzx", "指挥中心");
		map.put("gaj", "公安局");
		map.put("sxxzx", "市信息中心");
		return map;
	}

	public static Map<String, String> getXZFWZXTradeMap(){
		xztradeMap.put("1", "公交");
		xztradeMap.put("2", "出租");
		xztradeMap.put("3", "停车");
		xztradeMap.put("4", "货运");
		xztradeMap.put("5", "汽修");
		xztradeMap.put("6", "外商");
		xztradeMap.put("7", "驾培");
		xztradeMap.put("8", "长客");
		xztradeMap.put("9", "港口");
		xztradeMap.put("15", "轨道");
		return xztradeMap;
	}

	public static Map<String, String> getKSTradeMap(){
		kstradeMap.put("101", "公交电车");
		kstradeMap.put("201", "客运出租");
		kstradeMap.put("501", "货物运输");
		kstradeMap.put("601", "机动车维修");
		kstradeMap.put("701", "机动车驾培");
		return kstradeMap;
	}

	public static Map<String, String> getZFTradeMap(){
		zftradeMap.put("101", "公交");
		zftradeMap.put("201", "出租");
		zftradeMap.put("301", "轨道");
		zftradeMap.put("401", "长客");
		zftradeMap.put("501", "货运");
		zftradeMap.put("601", "汽修");
		zftradeMap.put("701", "驾培");
		zftradeMap.put("801", "停车");
		zftradeMap.put("901", "清障");
		zftradeMap.put("1001", "控烟");
		zftradeMap.put("1011", "非法客运");
		zftradeMap.put("1111", "公路路政");
		zftradeMap.put("1112", "城市路政");
		zftradeMap.put("1012", "其他");
		zftradeMap.put("5012", "危货");
		zftradeMap.put("5013", "集装箱");
		return zftradeMap;
	}

	public static Map<String,String> getVehTradeMap(){
		vehtradeMap.put("101", "公交电车");
		vehtradeMap.put("201", "客运出租");
		vehtradeMap.put("401", "长途客运");
		vehtradeMap.put("701", "机动车驾培");
		vehtradeMap.put("901", "清障施救");
		vehtradeMap.put("5011", "普通货运");
		vehtradeMap.put("5014", "危险货运");
		return vehtradeMap;
	}
	public static boolean sql_inj(String str) {
		//防止sql注入？
		String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|+";
		// | 特殊字符需要转义，而jdk1.8 因容错性较好而不需转义
		String[] inj_stra = inj_str.split("\\|");
		for (int i = 0; i < inj_stra.length; i++) {
			if (str.indexOf(inj_stra[i]) >=0 ) {
				return true;
			}
		}
		return false;
	}


	/**
	 * @param str
	 * @return
	 * 2017年4月5日
	 * @author gcr
	 */
	public static String null2Empty(Object str) {
		if(str==null){
			return "";
		}else{
			return str.toString();
		}
	}


	/**
	 * 字典从内存中获取初始化的map字典
	 * key=code value=name
	 * @param dicType
	 * @return
	 */
	public static Map<String, String> returnDicMap(String dicType){
		//排序
		Map<String, String> mapDic = new LinkedHashMap<>();
		Map<String,List<AuthDic>> map = InitCommonSourceEnum.INSTANCE.dicMap;
		if(map!=null&&map.size()!=0){
			List<AuthDic> listDic = map.get(dicType);
			if(!CollectionUtils.isEmpty(listDic)){
				//排序
				listDic=listDic.stream().sorted((a, b) -> a.getSeq() - b.getSeq()).collect(Collectors.toList());
				for(AuthDic dic : listDic){
					mapDic.put(dic.getCode(), dic.getName());
				}
			}
		}
		return mapDic;
	}

	/**
	 * 字典从内存中获取初始化的map字典
	 * key=name, value=code
	 * @param dicType
	 * @return
	 */
	public static Map<String, String> returnDicMap2(String dicType){
		Map<String, String> mapDic = new HashMap<String, String>();
		Map<String,List<AuthDic>> map = InitCommonSourceEnum.INSTANCE.dicMap;
		if(map!=null&&map.size()!=0){
			List<AuthDic> listDic = map.get(dicType);
			for(AuthDic dic : listDic){
				mapDic.put(dic.getName(), dic.getCode());
			}
		}
		return mapDic;
	}

	/**
	 * 为实体对象添加新增人和时间等信息
	 *
	 * @param t 实体对象
	 * @param authUser 登陆的用户
	 * @param <T>
	 */
	public static <T extends EntityTemplate> void setCreateInfo(T t, AuthUser authUser){
		Date date = new Date();
		if (Objects.isNull(t.getCrtDate())){
			t.setCrtUser(authUser.getUserName());
			t.setCrtDate(date);
		}
		t.setUpdUser(authUser.getUserName());
		t.setUpdDate(date);
		t.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
	}

	/**
	 * 为实体对象添加更新人和时间等信息
	 *
	 * @param t 实体对象
	 * @param authUser 登陆的用户
	 * @param <T>
	 */
	public static <T extends EntityTemplate> void setUpdateInfo(T t, AuthUser authUser){
		t.setUpdUser(authUser.getUserName());
		t.setUpdDate(new Date());
	}

	/**
	 * 判断对象是否为null（所有属性）
	 *
	 * @param object
	 * @return
	 */
	public static boolean ObjectIsNull(Object object) {
		if (null == object) {
			return true;
		}

		try {
			for (Field f : object.getClass().getDeclaredFields()) {
				f.setAccessible(true);
				if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
